package myJs

import myJs.Utils.g
import myJs.implicits.Implicits._
import myJs.myPkg.Implicits._
import myJs.myPkg.jquery._
import myJs.myPkg.{ColumnOptions, ExportOptions, TableOptions}
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._
import shared.VarTool

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}


/**
 * Created by yz on 11/5/2020
 */
@JSExportTopLevel("Download")
object Download {

  val tableId = "table"

  @JSExport("init")
  def init = {
    initTable
    refreshTable

  }

  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val downloadUrl = g.jsRoutes.controllers.DownloadController.downloadData().url.toString
      val downloadStr = a(title := "下载结果",
        href := s"${downloadUrl}?fileName=${row("fileName")}", cursor.pointer,
        img(src := "/assets/images/txt.png")
      )
      downloadStr
  }

  val operateColumn = js.Array(
    ColumnOptions.field("operate").title("Download").formatter(operateFmt).filterControl("clear")
  )


  def refreshTable = {
    refreshLsTable
  }

  def refreshLsTable = {
    val data = VarTool.types.map { kind =>
      js.Dictionary("fileName" -> s"${kind}_expr.tar.gz")
    }.toJSArray
    $(s"#table").bootstrapTable("load", data)
  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case _ => v
  }

  def initLsTable = {
    val maps = SeqMap("fileName" -> "File name")
    val columns = maps.map { case (fieldName, title) =>
      val fmt = tbFmt(fieldName)
      val basicOptions = ColumnOptions.field(fieldName).title(title).formatter(fmt)
      fieldName match {
        case _ => basicOptions
      }
    }.toJSArray.concat(operateColumn)
    val pageList = js.Array("5", "10", "All")
    val options = TableOptions.columns(columns.toJSArray).pagination(true).pageList(pageList).
      pageSize(pageList.head.toInt)
    $(s"#${tableId}").bootstrapTable(options)
    bindEvt
  }

  def initTable = {
    initLsTable
  }

  def bindEvt = {

  }


}
